<template>
  <div class="dewormings-form">
    <el-card shadow="never">
      <template #header>
        <div class="page-header">
          <h2>{{ isEdit ? '编辑驱虫记录' : '添加驱虫记录' }}</h2>
          <el-button @click="$router.back()">返回</el-button>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        class="form-container"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="宠物编号" prop="petId">
              <el-input v-model.number="formData.petId" placeholder="请输入宠物编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="驱虫药类型" prop="dewormerType">
              <el-input v-model="formData.dewormerType" placeholder="请输入驱虫药类型" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="品牌" prop="dewormingsBrand">
              <el-input v-model="formData.dewormingsBrand" placeholder="请输入品牌" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="驱虫日期" prop="dewormingsDate">
              <el-date-picker
                v-model="formData.dewormingsDate"
                type="date"
                placeholder="选择驱虫日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="下次驱虫日期" prop="nextdueDate">
              <el-date-picker
                v-model="formData.nextdueDate"
                type="date"
                placeholder="选择下次驱虫日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="驱虫人员" prop="dewormingsAdministered">
              <el-input v-model="formData.dewormingsAdministered" placeholder="请输入驱虫人员" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit" :loading="loading">
            {{ isEdit ? '更新' : '保存' }}
          </el-button>
          <el-button @click="handleCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { dewormingsApi } from '@/api'
import type { Dewormings } from '@/types'

const router = useRouter()
const route = useRoute()

const formRef = ref<FormInstance>()
const loading = ref(false)

// 判断是否为编辑模式
const isEdit = computed(() => {
  return route.params.id !== undefined
})

// 表单数据
const formData = reactive<Dewormings>({
  dewormingId: undefined,
  petId: undefined,
  dewormerType: '',
  dewormingsBrand: '',
  dewormingsDate: '',
  nextdueDate: '',
  dewormingsAdministered: ''
})

// 表单验证规则
const formRules: FormRules = {
  petId: [
    { required: true, message: '请输入宠物编号', trigger: 'change' }
  ],
  dewormerType: [
    { required: true, message: '请输入驱虫药类型', trigger: 'change' }
  ],
  dewormingsBrand: [
    { required: true, message: '请输入品牌', trigger: 'change' }
  ],
  dewormingsDate: [
    { required: true, message: '请选择驱虫日期', trigger: 'change' }
  ],
  nextdueDate: [
    { required: true, message: '请选择下次驱虫日期', trigger: 'change' }
  ],
  dewormingsAdministered: [
    { required: true, message: '请输入驱虫人员', trigger: 'change' }
  ]
}

// 获取驱虫记录详情
const fetchDewormingDetail = async (id: number) => {
  try {
    const response = await dewormingsApi.getById(id)
    if (response.code === 200) {
      Object.assign(formData, response.data)
    } else {
      ElMessage.error(response.message || '获取驱虫记录详情失败')
    }
  } catch (error) {
    console.error('获取驱虫记录详情失败:', error)
    ElMessage.error('获取驱虫记录详情失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    loading.value = true
    
    // 准备提交的数据
    const submitData = { ...formData }
    
    // 如果是添加操作，不传递petId字段
    if (!isEdit.value) {
      delete submitData.petId
    }
    
    console.log('提交的驱虫数据:', submitData)
    console.log('提交的驱虫数据JSON:', JSON.stringify(submitData, null, 2))
    
    let response
    if (isEdit.value) {
      response = await dewormingsApi.update(submitData)
    } else {
      response = await dewormingsApi.add(submitData)
    }
    
    if (response.code === 200) {
      ElMessage.success(isEdit.value ? '更新成功' : '添加成功')
      router.push('/medical-manage/dewormings')
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    console.error('提交表单失败:', error)
    console.error('错误详情:', error.response?.data || error)
    ElMessage.error('提交失败，请检查网络或表单数据。')
  } finally {
    loading.value = false
  }
}

// 取消操作
const handleCancel = () => {
  router.push('/medical-manage/dewormings')
}

onMounted(() => {
  if (isEdit.value) {
    const dewormingId = Number(route.params.id)
    if (dewormingId) {
      fetchDewormingDetail(dewormingId)
    }
  }
})
</script>

<style scoped>
.dewormings-form {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.form-container {
  max-width: 800px;
  margin: 0 auto;
}
</style> 